package org.easy.tool.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

/**
 * @author Valley
 * Created by Valley on 2023/7/18 11:28
 */
public class SecureUtil {

    public static String publicKey = "";
    public static String privateKey = "";
    private static RSA rsa = new RSA();
    private static final int AES_KEY_LEN = 16;
    private static final String AES_KEY_DEFAULT = "h2f9mijjiqzptvr4";

    static {
        publicKey = rsa.getPublicKeyBase64();
        privateKey = rsa.getPrivateKeyBase64();
    }

    /**
     * 功能：更新rsa密钥
     */
    public static boolean updateRSA() {
        rsa = new RSA();
        return true;
    }

    /**
     * 功能：进行rsa公钥加密
     */
    public static String publicEncode(String raw) {
        return rsa.encryptBase64(raw, KeyType.PublicKey);
    }

    /**
     * 功能：进行rsa私钥解密
     */
    public static String privateDecode(String encode) {
        return rsa.decryptStr(encode, KeyType.PrivateKey);
    }


    /**
     * 功能：进行base64加密
     */
    public static String base64Encode(String raw) {
        return Base64.encode(raw);
    }

    /**
     * 功能：进行base64解密
     */
    public static String base64Decode(String encode) {
        return Base64.decodeStr(encode);
    }


    /**
     * 功能：进行aes对称加密，密钥必须为16位
     */
    public static String aesEncode(String raw, String key) {
        StringBuilder keyBuilder = new StringBuilder(key);
        while (keyBuilder.length() < AES_KEY_LEN){
            keyBuilder.append(keyBuilder);
        }
        key = StringUtil.sub(keyBuilder.toString(), 0, AES_KEY_LEN);
        return cn.hutool.crypto.SecureUtil.aes(key.getBytes()).encryptBase64(raw);
    }

    /**
     * 功能：进行aes对称加密
     */
    public static String aesEncode(String raw) {
        return aesEncode(raw, AES_KEY_DEFAULT);
    }

    /**
     * 功能：进行aes解密，密钥必须为16位
     */
    public static String aesDecode(String encode, String key) {
        StringBuilder keyBuilder = new StringBuilder(key);
        while (keyBuilder.length() < AES_KEY_LEN){
            keyBuilder.append(keyBuilder);
        }
        key = StringUtil.sub(keyBuilder.toString(), 0, AES_KEY_LEN);
        return cn.hutool.crypto.SecureUtil.aes(key.getBytes()).decryptStr(encode);
    }

    /**
     * 功能：进行aes解密，密钥必须为16位
     */
    public static String aesDecode(String encode) {
        try {
            return aesDecode(encode, AES_KEY_DEFAULT);
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 功能：进行md5加密
     */
    public static String md5Encode(String raw) {
        return cn.hutool.crypto.SecureUtil.md5(raw);
    }

    /**
     * 功能：进行md5匹配
     */
    public static boolean md5Match(String raw, String encode) {
        return StringUtil.equals(raw, md5Encode(encode));
    }

}
